<template>
  <el-dialog :modelValue="modelValue" title="权限调整" width="80%" align-center class="public-dialog" @close="handleClose" draggable destroy-on-close>
    <div class="content" v-loading="loading">
      <div class="name">
        <span>英文名: {{ authorityData?.userinfo?.en_name || "-" }}</span>
        <span>真实姓名: {{ authorityData?.userinfo?.realname || "-" }}</span>
      </div>
      <!-- 分配权限 -->
      <div>
        <div class="role">
          <el-tag class="mx-1" type="info" effect="plain" size="large" :round="true" v-for="(item, index) in authorityData?.roles || []" :key="index">{{ item.role_name }}</el-tag>
        </div>

        <div class="radio">
          <el-radio-group v-model="radioType" @change="handleradioType">
            <el-radio v-for="item in radioTypeData" :key="item.value" :label="item.value" size="large">{{ item.label }}</el-radio>
          </el-radio-group>
          <el-link type="primary" :underline="false" @click="clearCustomize" v-if="radioType == 'all'">清除账户自定义权限</el-link>
        </div>
        <el-tabs type="border-card" class="tab-pane">
          <!-- ---------- 数据权限 ---------- -->
          <el-tab-pane label="菜单权限">
            <div class="m-[10px]">
              <el-cascader
                v-model="search_list.menu_name"
                :options="optionsData.menu_options"
                :props="cascaderProps.cascaderProps"
                class="w-full"
                placeholder="请搜索"
                filterable
                @remove-tag="handleMenuRemove"
                :filter-method="customFilterMethod"
              />
            </div>
            <el-cascader-panel
              v-if="tabPaneShow"
              :key="1"
              v-model="allAuth[radioType].menu_ids"
              ref="dataMenuRef"
              :options="optionsData.menu_options"
              :props="cascaderProps.cascaderProps"
              :class="`cascaderPanel ${radioType == 'all' ? '' : 'disabled'}`"
              @change="cascaderChange($event, dataMenuRef, 'menu_ids')"
            >
              <template #default="{ data, node }">
                <div class="flex">
                  <div class="flex-1">{{ data.name }}</div>
                  <!-- 禁用权限 -->
                  <span v-if="getDisableOwner(node, 'menu_ids')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                  <!-- 自定义权限 -->
                  <span v-if="getUserOwner(node, 'menu_ids')" class="text-[12px] text-[red]"> 自定义权限 </span>
                </div>
              </template>
            </el-cascader-panel>
          </el-tab-pane>

          <!-- ---------- 按钮授权 ---------- -->
          <el-tab-pane label="按钮授权">
            <div class="m-[10px]">
              <el-cascader
                v-model="search_list.button_name"
                :options="optionsData.button_options"
                :props="cascaderProps.cascaderProps"
                class="w-full"
                placeholder="请搜索"
                filterable
                @remove-tag="handleButtonRemove"
                :filter-method="customFilterMethod"
              />
            </div>
            <el-cascader-panel
              v-if="tabPaneShow"
              :key="2"
              v-model="allAuth[radioType].button_ids"
              ref="dataButtonRef"
              :options="optionsData.button_options"
              :props="cascaderProps.cascaderProps"
              :class="`cascaderPanel ${radioType == 'all' ? '' : 'disabled'}`"
              @change="cascaderChange($event, dataButtonRef, 'button_ids')"
            >
              <template #default="{ data, node }">
                <div class="flex">
                  <div class="flex-1">{{ data.name }}</div>
                  <!-- 禁用权限 -->
                  <span v-if="getDisableOwner(node, 'button_ids')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                  <!-- 自定义权限 -->
                  <span v-if="getUserOwner(node, 'button_ids')" class="text-[12px] text-[red]"> 自定义权限 </span>
                </div>
              </template>
            </el-cascader-panel>
          </el-tab-pane>
          <!-- ---------- 数据权限 ---------- -->
          <el-tab-pane label="数据权限">
            <div class="m-[10px]">
              <el-cascader
                v-model="search_list.data_user_name"
                :options="optionsData.data_options"
                :props="cascaderProps.useCascaderProps"
                class="w-full"
                placeholder="请搜索"
                filterable
                @remove-tag="handleDataRemove"
                :filter-method="customFilterMethod"
              />
            </div>
            <el-cascader-panel
              v-if="tabPaneShow"
              :key="3"
              ref="dataUserRef"
              v-model="allAuth[radioType].data_user_ids"
              :options="optionsData.data_options"
              :props="cascaderProps.useCascaderProps"
              :class="`cascaderPanel ${radioType == 'all' ? '' : 'disabled'}`"
              @change="cascaderChange($event, dataUserRef, 'data_user_ids')"
            >
              <template #default="{ data, node }">
                <div class="flex">
                  <div class="flex-1">{{ data.name }}</div>
                  <!-- 禁用权限 -->
                  <span v-if="getDisableOwner(node, 'data_user_ids')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                  <!-- 自定义权限 -->
                  <span v-if="getUserOwner(node, 'data_user_ids')" class="text-[12px] text-[red]"> 自定义权限 </span>
                </div>
              </template>
            </el-cascader-panel>
          </el-tab-pane>
          <!-- ---------- 属性权限 ---------- -->
          <el-tab-pane label="属性权限">
            <div class="attribute">
              <div>
                <div class="text">商品权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.goods_category_name"
                    :props="cascaderProps.goodsSearchProps"
                    :options="optionsData.goods_category_options"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleGoodsRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
                <el-tree
                  v-if="tabPaneShow"
                  :key="4"
                  :props="cascaderProps.goodsProps"
                  :data="optionsData.goods_category_options"
                  :default-checked-keys="allAuth[radioType].goods_category_ids"
                  show-checkbox
                  ref="dataGoodsRef"
                  :class="`tree ${radioType == 'all' ? '' : 'disabled'}`"
                  node-key="id"
                  @check="goodsCurrentChange"
                >
                  <template #default="{ data, node }">
                    <div class="flex w-[80%]">
                      <div class="flex-1">{{ data.name }}</div>
                      <!-- 禁用权限 -->
                      <span v-if="getDisableOwner(data, 'goods_category_ids', 'id')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                      <!-- 自定义权限 -->
                      <span v-if="getUserOwner(data, 'goods_category_ids', 'id')" class="text-[12px] text-[red]"> 自定义权限 </span>
                    </div>
                  </template>
                </el-tree>
              </div>
              <div class="ml-[8px] mr-[8px]">
                <div class="text">仓库权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.warehouse_name"
                    :props="cascaderProps.warehouseSearchProps"
                    :options="optionsData.warehouse_options"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleWarehouseRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
                <el-tree
                  :key="5"
                  :props="cascaderProps.warehouseProps"
                  :data="optionsData.warehouse_options"
                  show-checkbox
                  :default-checked-keys="allAuth[radioType].warehouse_ids"
                  :class="`tree ${radioType == 'all' ? '' : 'disabled'}`"
                  node-key="warehouse_id"
                  ref="dataWarehouseRef"
                  @check="warehouseCurrentChange"
                >
                  <template #default="{ data, node }">
                    <div class="flex w-[80%]">
                      <div class="flex-1">{{ data.warehouse_name }}</div>
                      <!-- 禁用权限 -->
                      <span v-if="getDisableOwner(data, 'warehouse_ids', 'warehouse_id')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                      <!-- 自定义权限 -->
                      <span v-if="getUserOwner(data, 'warehouse_ids', 'warehouse_id')" class="text-[12px] text-[red]"> 自定义权限 </span>
                    </div>
                  </template>
                </el-tree>
              </div>
              <div>
                <div class="text">字段权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.field_name"
                    :props="cascaderProps.menuSearchProps"
                    :options="optionsData.field_attr_options"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleFieldRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
                <el-tree
                  :key="6"
                  :props="cascaderProps.menuProps"
                  :data="optionsData.field_attr_options"
                  show-checkbox
                  :default-checked-keys="allAuth[radioType].field_attr_ids"
                  :class="`tree ${radioType == 'all' ? '' : 'disabled'}`"
                  ref="dataFieldRef"
                  node-key="id"
                  @check="fieldAttrCurrentChange"
                >
                  <template #default="{ data, node }">
                    <div class="flex w-[80%]">
                      <div class="flex-1">{{ data.name }}</div>
                      <!-- 禁用权限 -->
                      <span v-if="getDisableOwner(data, 'field_attr_ids', 'id')" class="text-[12px] text-[var(--el-color-primary)]"> 启动权限 </span>
                      <!-- 自定义权限 -->
                      <span v-if="getUserOwner(data, 'field_attr_ids', 'id')" class="text-[12px] text-[red]"> 自定义权限 </span>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="mt-[15px] text-[red]">提示 : 只能修改账号自定义权限,不能调整账号角色的权限</div>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button @click="handleClose(true)">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading" v-if="radioType == 'all'"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="VRole">
import { ElMessage } from "element-plus"
import {
  radioTypeData,
  cascaderProps,
  transformData,
  oneArray,
  recursivelyAddDisabled,
  convertIdToDid,
  transformIds,
  updateDepartmentIds,
  simplifyIds,
  filterTreeByIds,
  filterTreeByKeyword,
} from "./data"
import { organizationList } from "@/api/system/role"
import { getMenus } from "@/api/menu"
import api from "../../api"
import { flattenAndRemoveDuplicates } from "@/utils/tools.js"
import { reactive } from "vue"
// 声明接收参数
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  id: { type: [String, Number], default: "" },
})

const emit = defineEmits(["update:modelValue", "refresh", "close"])
const loading = ref(false)

const authorityData = ref({}) // 当前用户 所有权限配置 存档

const dataMenuRef = ref() // 菜单权限
const dataButtonRef = ref() // 按钮授权
const dataUserRef = ref() // 数据权限
const dataGoodsRef = ref() // 商品权限
const dataWarehouseRef = ref() // 仓库权限
const dataFieldRef = ref() // 字段权限

// 用户 所有权限类型  数据
const allAuth = ref({
  all: {
    menu_ids: [],
    button_ids: [],
    data_dept_ids: [],
    data_user_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
    field_attr_ids: [],
  },
  role_owner: {
    menu_ids: [],
    button_ids: [],
    data_dept_ids: [],
    data_user_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
    field_attr_ids: [],
  },
  user_owner: {
    menu_ids: [],
    button_ids: [],
    data_dept_ids: [],
    data_user_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
    field_attr_ids: [],
  },
})

// 商品权限
const goodsCurrentChange = (e, checked) => {
  console.log(checked)
  console.log(dataGoodsRef.value.getCheckedKeys())

  allAuth.value.all.goods_category_ids = checked.checkedKeys
  all.value.goods_category_ids = [...checked.checkedKeys]
}
// 仓库权限
const warehouseCurrentChange = (e, checked) => {
  allAuth.value.all.warehouse_ids = checked.checkedKeys
  all.value.warehouse_ids = [...checked.halfCheckedKeys, ...checked.checkedKeys]
}
// 字段权限
const fieldAttrCurrentChange = (e, checked) => {
  allAuth.value.all.field_attr_ids = checked.checkedKeys
  all.value.field_attr_ids = [...checked.halfCheckedKeys, ...checked.checkedKeys]
}

// 级连 选项改动
const cascaderChange = (e, ref, key = "", init = false) => {
  setTimeout(async () => {
    console.log("==========     cascaderChange     ==========")
    let data = ref?.getCheckedNodes().map((v) => v.pathValues)
    data = [...new Set(data.flat())]
    if (!init && key == "data_user_ids") {
      if (all.value[key].length < data.length) {
        // 添加
        console.log("添加")
        let values = data.filter((v) => !all.value[key].includes(v))
        let allData = getCateUserIdsObj(values, "data_user_ids", "del")
        allData = [...new Set([e[e.length - 1], ...allAuth.value.all[key], ...allData])]
        allAuth.value.all[key] = allData
      } else {
        // 删除
        console.log("删除")
        let values = all.value[key].filter((v) => !data.includes(v))
        allAuth.value.all[key] = getCateUserIdsObj(values, "data_user_ids", "add")
      }
      await nextTick()
      data = ref?.getCheckedNodes().map((v) => v.pathValues)
      data = [...new Set(data.flat())]
    }

    all.value[key] = data
    data = null
  }, 100)
}

// 数据权限 调整各部门下 同一人员   values： 前后差异数据，key： 数据权限字段  type： 新增或删除
const getCateUserIdsObj = (values, key, type = "") => {
  values = values.map((v) => (typeof v == "string" ? Number(v.split("_")[0]) : v))
  values = [...new Set(values)].filter(Boolean)
  let ondata = values.filter((v) => cateUserIdsObj.value[v])

  if (type == "add") {
    // 添加
    return allAuth.value.all[key].filter((v) => {
      return typeof v == "string" ? !ondata?.includes(Number(v?.split("_")?.[0])) : !ondata.includes(v)
    })
  } else {
    // 删除
    let allId = []
    ondata.forEach((v) => {
      if (cateUserIdsObj.value[v]) {
        for (let index = 0; index < cateUserIdsObj.value[v]; index++) {
          allId.push(index == 0 ? v : `${v}_${index}`)
        }
      }
    })
    return allId
  }
}
// 已选择数据 包括父级半选状态  用于 自定义添加 & 自定义 禁用权限判断
const all = ref({
  menu_ids: [],
  button_ids: [],
  data_dept_ids: [],
  data_user_ids: [],
  goods_category_ids: [],
  warehouse_ids: [],
  field_attr_ids: [],
})

// 自定义权限
const getUserOwner = (data, key = "", nodeKey = "value") => {
  if (radioType.value == "all") {
    return (allAuth.value?.[radioType.value]?.[key].includes(data[nodeKey]) || all.value[key].includes(data[nodeKey])) && !baseRoleOwner.value[key].includes(data[nodeKey])
  } else {
    return false
  }
}
// 禁用权限
const getDisableOwner = (data, key = "", nodeKey = "value") => {
  if (radioType.value == "all") {
    return baseRoleOwner.value[key]?.includes(data[nodeKey]) && !all.value[key]?.includes(data[nodeKey])
  } else {
    return false
  }
}

onMounted(async () => {
  getBaseData()
})

// 商品权限  末级id  角色权限会把 半选 状态传回 须过滤
const goodsLastStageId = ref([])
const optionsDataBox = ref({})
const optionsData = ref({})
const cateUserIds = ref([])
// 人员重复次数
const cateUserIdsObj = ref({})
const getBaseData = async () => {
  try {
    let res1 = await api.baseData({ get: ["access"] })
    let warehouseData = transformData(res1?.data?.access?.warehouse_options || [])
    let fieldData = convertIdToDid(res1?.data?.access?.field_attr_options || [])
    optionsDataBox.value = res1.data.access
    optionsDataBox.value.warehouse_options = warehouseData
    optionsDataBox.value.field_attr_options = fieldData
    let res2 = await organizationList()
    const { updatedTree, duplicateUserIds } = updateDepartmentIds(res2.data)
    optionsDataBox.value.data_options = updatedTree

    cateUserIds.value = duplicateUserIds
    // 人员重复次数
    cateUserIds.value.forEach((v) => {
      cateUserIdsObj.value = { ...cateUserIdsObj.value, ...v }
    })
    // 获取商品权限 末级id (用于过滤)
    goodsLastStageId.value = getGoodsLastStageId(optionsDataBox.value.goods_category_options)
  } catch (error) {}
}

const handleClick = (e) => {
  //
}
watch(
  () => props.id,
  async (val) => {
    if (val) {
      optionsData.value = { ...optionsDataBox.value }
      // await getBaseData()
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)
// 商品权限 过滤父级id前  存档
const baseRoleOwnerGoods = ref({})
//详情
const getDetail = async (id) => {
  radioType.value = "role_owner"
  try {
    const { data } = await api.getAccess({ id })
    // 商品权限 过滤父级id前  存档
    baseRoleOwnerGoods.value = [...data?.perm.role_owner.goods_category_ids]
    // 过滤 商品权限 父级菜单
    if (data?.perm) {
      for (const key in data.perm) {
        let item = data.perm[key]

        // 商品权限  末级id
        item.goods_category_ids = item.goods_category_ids.filter((v) => !goodsLastStageId.value.includes(v))
        // 数据权限
        let personnel = transformIds(cateUserIds.value, item.data_user_ids || [])
        item.data_user_ids = personnel
      }
    }

    // 商品权限  末级id
    if (data?.user_disable_perm?.goods_category_ids) {
      data.user_disable_perm.goods_category_ids = data.user_disable_perm.goods_category_ids.filter((v) => !goodsLastStageId.value.includes(v))
    }

    authorityData.value = JSON.parse(JSON.stringify(data))

    // 初始化角色配置 缓存信息并加载全部配置

    await initRoleOwner()
  } catch (error) {}
}

const baseRoleOwner = ref({}) // 用户角色配置 回显数据
// 初始化角色配置 缓存信息并加载全部配置
const initRoleOwner = async () => {
  try {
    loading.value = true
    let data = JSON.parse(JSON.stringify(authorityData.value))
    await nextTick()

    allAuth.value = data.perm

    await setTimeout(async () => {
      // 获取当前视图 已选项目
      baseRoleOwner.value = getViewCheck("pathValues")

      baseRoleOwner.value.goods_category_ids = baseRoleOwnerGoods.value
      baseRoleOwner.value.warehouse_ids = [...dataWarehouseRef.value.getCheckedKeys(), ...dataWarehouseRef.value.getHalfCheckedKeys()]
      baseRoleOwner.value.field_attr_ids = [...dataFieldRef.value.getCheckedKeys(), ...dataFieldRef.value.getHalfCheckedKeys()]

      console.log("-------------   baseRoleOwner   -------------------")
      console.log(baseRoleOwner.value)
      await nextTick()

      setTimeout(() => {
        handleradioType("all")
      }, 100)
    }, 100)
  } catch (error) {
    loading.value = false
  }
}

// 当前权限类型切换  all：角色+用户   role_owner：角色   user_owner：用户
const radioType = ref("role_owner")
const handleradioType = async (val) => {
  try {
    loading.value = true
    radioType.value = val

    console.log("handleradioType")
    let data = JSON.parse(JSON.stringify(authorityData.value))

    await nextTick()
    for (let key in search_list) {
      search_list[key] = []
    }
    if (val == "all") {
      // 角色+用户 过滤禁用字段
      for (const key in data.user_disable_perm) {
        let row = data.user_disable_perm[key]
        data.perm.all[key] = data.perm.all[key].filter((v) => !row.includes(v))
      }
    }
    // 回显 商品权限 选项
    dataGoodsRef.value.setCheckedKeys(data.perm?.[radioType.value].goods_category_ids || [])
    dataWarehouseRef.value.setCheckedKeys(data.perm?.[radioType.value].warehouse_ids || [])
    dataFieldRef.value.setCheckedKeys(data.perm?.[radioType.value].field_attr_ids || [])

    allAuth.value = data.perm
    await nextTickTabPaneShow()
    loading.value = false
    if (val == "all") {
      setTimeout(async () => {
        cascaderChange(false, dataMenuRef.value, "menu_ids", true)
        cascaderChange(false, dataButtonRef.value, "button_ids", true)
        cascaderChange(false, dataUserRef.value, "data_user_ids", true)
        all.value.goods_category_ids = [
          ...dataGoodsRef.value.getCheckedKeys(),
          // ...dataGoodsRef.value.getHalfCheckedKeys(),
        ]
        all.value.warehouse_ids = [...dataWarehouseRef.value.getCheckedKeys(), ...dataWarehouseRef.value.getHalfCheckedKeys()]
        all.value.field_attr_ids = [...dataFieldRef.value.getCheckedKeys(), ...dataFieldRef.value.getHalfCheckedKeys()]
      }, 100)
    }
  } catch (error) {
    loading.value = false
  }
}

//清除账户自定义权限
const clearCustomize = () => {
  let data = JSON.parse(JSON.stringify(authorityData.value))
  authorityData.value.perm.all = authorityData.value.perm.role_owner
  for (const key in authorityData.value.user_disable_perm) {
    authorityData.value.user_disable_perm[key] = []
  }

  handleradioType("all")
}

const handleSave = async () => {
  try {
    let { user_owner, user_disable_perm } = getSaveData()
    let perm = {
      all: {
        menu_ids: [],
        button_ids: [],
        data_user_ids: [],
        goods_category_ids: [],
        warehouse_ids: [],
        field_attr_ids: [],
      },
      role_owner: {
        menu_ids: [],
        button_ids: [],
        data_user_ids: [],
        goods_category_ids: [],
        warehouse_ids: [],
        field_attr_ids: [],
      },
      user_owner,
    }
    // roles
    // let data = JSON.parse(JSON.stringify(authorityData.value))
    // return
    // const { roles, userinfo } = data
    let params = {
      roles: authorityData.value.roles,
      userinfo: authorityData.value.roles,
      id: props.id,
      perm,
      user_disable_perm,
    }
    // console.log(user_owner)
    // console.log(user_disable_perm)
    // return
    loading.value = true
    const { code, message } = await api.setAccess(params)
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success("保存成功!")
    handleClose(true)

    // for (let key in allAuth.value) {
    //   for (let k in allAuth.value[key]) {
    //     allAuth.value[key][k] = flattenAndRemoveDuplicates(allAuth.value[key][k])
    //   }
    // }

    // console.log(data)
  } catch (error) {
    console.log(error)

    loading.value = false
  } finally {
    loading.value = false
  }
}

const handleClose = async (refresh) => {
  authorityData.value = {}
  // radioType.value = "all"
  optionsData.value = {}
  optionsData.value = {}
  all.value = {
    menu_ids: [],
    button_ids: [],
    data_dept_ids: [],
    data_user_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
    field_attr_ids: [],
  }
  allAuth.value = {
    all: {
      menu_ids: [],
      button_ids: [],
      data_dept_ids: [],
      data_user_ids: [],
      goods_category_ids: [],
      warehouse_ids: [],
      field_attr_ids: [],
    },
    role_owner: {
      menu_ids: [],
      button_ids: [],
      data_dept_ids: [],
      data_user_ids: [],
      goods_category_ids: [],
      warehouse_ids: [],
      field_attr_ids: [],
    },
    user_owner: {
      menu_ids: [],
      button_ids: [],
      data_dept_ids: [],
      data_user_ids: [],
      goods_category_ids: [],
      warehouse_ids: [],
      field_attr_ids: [],
    },
  }
  for (let key in search_list) {
    search_list[key] = []
  }
  setTimeout(() => {
    emit("update:modelValue", false)
    emit("close")
    if (refresh) emit("refresh")
  }, 200)
}

// --------------------------------------------------------

const getSaveData = () => {
  console.log("-------------   getSaveData   -------------------")
  console.time(11111)

  let emitPathValue = getViewCheck("pathValues")
  let pathValue = getViewCheck("value")
  // console.log("emitPathValue")
  // console.log(emitPathValue)
  // console.log('pathValue')
  // console.log(pathValue)
  // console.log(baseRoleOwner.value)

  console.log("-------------   自定义 添加   -------------------")
  let user_owner = {
    menu_ids: [],
    button_ids: [],
    data_dept_ids: [],
    data_user_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
    field_attr_ids: [],
  }
  // 菜单权限 许传父级全选 或 半选状态
  user_owner.menu_ids = emitPathValue.menu_ids.filter((v) => !baseRoleOwner.value?.menu_ids.includes(v) && emitPathValue.menu_ids.includes(v))
  // console.log("menu_ids")
  // console.log(menu_ids)
  user_owner.button_ids = emitPathValue.button_ids.filter((v) => !baseRoleOwner.value?.button_ids.includes(v) && pathValue.button_ids.includes(v))

  // let data_user_ids = emitPathValue.data_user_ids.filter((v) => !baseRoleOwner.value?.data_user_ids.includes(v))
  // // 部门
  // user_owner.data_dept_ids = data_user_ids.filter((v) => String(v).includes("d")).map((v) => Number(v.replace("d", "")))
  // console.log("user_owner.data_dept_ids")
  // console.log(user_owner.data_dept_ids)

  let data_user_ids = pathValue.data_user_ids.filter((v) => !baseRoleOwner.value?.data_user_ids.includes(v))
  // 部门
  user_owner.data_dept_ids = data_user_ids.filter((v) => String(v).includes("d")).map((v) => Number(v.replace("d", "")))

  // 用户
  user_owner.data_user_ids = data_user_ids.filter((v) => !String(v).includes("d") && !String(v).includes("_"))

  // 商品权限 取全选字段  半选状态不传
  user_owner.goods_category_ids = allAuth.value.all.goods_category_ids.filter((v) => !baseRoleOwner.value?.goods_category_ids.includes(v))

  // 仓库权限  只取末级
  user_owner.warehouse_ids = allAuth.value.all.warehouse_ids.filter((v) => !baseRoleOwner.value?.warehouse_ids.includes(v))
  user_owner.warehouse_ids = user_owner.warehouse_ids.filter((v) => typeof v != "string")

  //  字段权限  只取末级
  user_owner.field_attr_ids = allAuth.value.all.field_attr_ids.filter((v) => !baseRoleOwner.value?.field_attr_ids.includes(v))
  user_owner.field_attr_ids = user_owner.field_attr_ids.filter((v) => !String(v).includes("d"))

  // console.log(user_owner)

  console.log("-------------  禁用  -------------")
  let user_disable_perm = {}
  user_disable_perm.menu_ids = baseRoleOwner.value?.menu_ids.filter((v) => !emitPathValue.menu_ids.includes(v))

  user_disable_perm.button_ids = baseRoleOwner.value?.button_ids.filter((v) => !emitPathValue.button_ids.includes(v))

  let values = baseRoleOwner.value?.data_user_ids.filter((v) => !emitPathValue.data_user_ids.includes(v))
  values = values.map((v) => (typeof v == "string" ? Number(v.split("_")[0]) : v))
  values = [...new Set(values)].filter(Boolean)
  // console.log(values);
  user_disable_perm.data_user_ids = values
  // 商品权限 取全选字段  半选状态不传
  user_disable_perm.goods_category_ids = baseRoleOwner.value?.goods_category_ids.filter((v) => !all.value.goods_category_ids.includes(v))
  // 仓库权限  只取末级
  user_disable_perm.warehouse_ids = baseRoleOwner.value?.warehouse_ids.filter((v) => !all.value.warehouse_ids.includes(v))
  user_disable_perm.warehouse_ids = user_disable_perm.warehouse_ids.filter((v) => typeof v != "string")
  //  字段权限  只取末级
  user_disable_perm.field_attr_ids = baseRoleOwner.value?.field_attr_ids.filter((v) => !all.value.field_attr_ids.includes(v))
  user_disable_perm.field_attr_ids = user_disable_perm.field_attr_ids.filter((v) => !String(v).includes("d"))

  // console.log(user_disable_perm)

  console.timeEnd(11111)
  return { user_owner, user_disable_perm }
}

// 获取当前视图 已选项目   value: 末级  pathValues: 全链路
const getViewCheck = (key = "") => {
  let role_owner = {
    menu_ids: [],
    button_ids: [],
    data_user_ids: [],
    field_attr_ids: [],
    goods_category_ids: [],
    warehouse_ids: [],
  }
  role_owner.menu_ids = dataMenuRef.value.getCheckedNodes().map((v) => v?.[key])
  role_owner.button_ids = dataButtonRef.value.getCheckedNodes().map((v) => v?.[key])
  role_owner.data_user_ids = dataUserRef.value.getCheckedNodes().map((v) => v?.[key])
  for (const key in role_owner) {
    role_owner[key] = [...new Set(role_owner[key].flat())]
  }
  return role_owner
}

// 获取商品权限 末级id
const getGoodsLastStageId = (list) => {
  let ids = []
  let fn = (data) => {
    data.forEach((item) => {
      if (item.son?.length) {
        ids.push(item.id)
        fn(item.son)
      }
    })
  }
  fn(list)
  return ids
}

// 重新渲染视图
const tabPaneShow = ref(true)
const nextTickTabPaneShow = () => {
  return new Promise((resolve, reject) => {
    tabPaneShow.value = false
    setTimeout(() => {
      tabPaneShow.value = true
      resolve()
    }, 100)
  })
}
const customFilterMethod = (node, keyword) => {
  return node.label.toLowerCase().includes(keyword.toLowerCase())
}
const search_list = reactive({
  menu_name: [], //菜单
  goods_category_name: [], //商品权限
  warehouse_name: [], //仓库权限
  field_name: [], //字段权限
  data_user_name: [], //数据权限
})
//商品权限
const changeGoodsData = () => {
  let obj = {
    checkedKeys: dataGoodsRef.value.getCheckedKeys(),
    halfCheckedKeys: dataGoodsRef.value.getHalfCheckedKeys(),
  }
  goodsCurrentChange("", obj)
}

const handleGoodsRemove = (val) => {
  dataGoodsRef.value.setChecked(val, false, true)
  setTimeout(() => {
    changeGoodsData()
  }, 200)
}
watch(
  () => search_list.goods_category_name,
  (val) => {
    if (!val.length) return
    let goodsData = dataGoodsRef.value.getCheckedKeys()
    const set = new Set([...goodsData, ...val])
    const setGood = Array.from(set)
    dataGoodsRef.value.setCheckedKeys(setGood)
    setTimeout(() => {
      changeGoodsData()
    }, 200)
  }
)
//仓库权限
const changeWarehouseData = () => {
  let obj = {
    checkedKeys: dataWarehouseRef.value.getCheckedKeys(),
    halfCheckedKeys: dataWarehouseRef.value.getHalfCheckedKeys(),
  }
  warehouseCurrentChange("", obj)
}
const handleWarehouseRemove = (val) => {
  dataWarehouseRef.value.setChecked(val, false, true)
  setTimeout(() => {
    changeWarehouseData()
  }, 200)
}
watch(
  () => search_list.warehouse_name,
  (val) => {
    if (!val.length) return
    let warehouseData = dataWarehouseRef.value.getCheckedKeys()
    const set = new Set([...warehouseData, ...val])
    const setWarehouse = Array.from(set)
    dataWarehouseRef.value.setCheckedKeys(setWarehouse)
    setTimeout(() => {
      changeWarehouseData()
    }, 200)
  }
)
//字段权限
const changeFieldData = () => {
  let obj = {
    checkedKeys: dataFieldRef.value.getCheckedKeys(),
    halfCheckedKeys: dataFieldRef.value.getHalfCheckedKeys(),
  }
  fieldAttrCurrentChange("", obj)
}
const handleFieldRemove = (val) => {
  dataFieldRef.value.setChecked(val, false, true)
  setTimeout(() => {
    changeFieldData()
  }, 200)
}
watch(
  () => search_list.field_name,
  (val) => {
    if (!val.length) return
    let fieldData = dataFieldRef.value.getCheckedKeys()
    const set = new Set([...fieldData, ...val])
    const setField = Array.from(set)
    dataFieldRef.value.setCheckedKeys(setField)
    setTimeout(() => {
      changeFieldData()
    }, 200)
  }
)
//菜单权限
const handleMenuRemove = (val) => {
  allAuth.value[radioType.value].menu_ids = allAuth.value[radioType.value].menu_ids.filter((item) => item !== val)
}
watch(
  () => search_list.menu_name,
  (val) => {
    if (!val.length) return
    const set = new Set([...allAuth.value[radioType.value].menu_ids, ...val])
    allAuth.value[radioType.value].menu_ids = Array.from(set)
  }
)
//按钮
const handleButtonRemove = (val) => {
  allAuth.value[radioType.value].button_ids = allAuth.value[radioType.value].button_ids.filter((item) => item !== val)
}
watch(
  () => search_list.button_name,
  (val) => {
    if (!val.length) return
    const set = new Set([...allAuth.value[radioType.value].button_ids, ...val])
    allAuth.value[radioType.value].button_ids = Array.from(set)
  }
)
//数据权限
const handleDataRemove = (val) => {
  allAuth.value[radioType.value].data_user_ids = allAuth.value[radioType.value].data_user_ids.filter((item) => item !== val)
  cascaderChange("", dataUserRef.value, "data_user_ids")
}
watch(
  () => search_list.data_user_name,
  (val) => {
    if (!val.length) return
    const set = new Set([...allAuth.value[radioType.value].data_user_ids, ...val])
    allAuth.value[radioType.value].data_user_ids = Array.from(set)
    cascaderChange("", dataUserRef.value, "data_user_ids")
  }
)
</script>
<style lang="scss" scoped>
.attribute {
  display: flex;
  height: 400px;
  overflow: auto;
  & > div {
    flex: 1;
    height: 100%;
    overflow: auto;
    border: 1px solid #e6e7e9;
    .text {
      text-align: center;
      line-height: 40px;
      background-color: var(--base-table-header-bg-color);
      color: #3487ff;
    }
  }
}
.content {
  align-items: center;
  .name {
    margin: 8px;
    span {
      margin-right: 20px;
    }
  }
  .role {
    margin: 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f7f9fe;
  }
  .radio {
    display: flex;
    margin: 0 15px;
    justify-content: space-between;
  }
  span {
    margin-left: 5px;
  }
}
.dialogName {
  font-size: 16px;
  font-weight: bold;
}
.input-switch {
  width: calc(100% - 58px);
  margin-right: 10px;
}
:deep(.tab-pane) {
  border-radius: 10px;
  min-height: 456px;
  .el-tabs__content {
    padding: 8px;
  }
  .el-tabs__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .el-tabs__nav {
    width: 100%;
    border-radius: 10px;
    display: flex;
  }
  .el-tabs__item.is-active {
    color: #fff !important;
    background-color: #3487ff !important;
  }
  .el-tabs__item {
    flex: 1;
    color: var(--base-tabs-color) !important;
    text-align: center;
    background: var(--base-color) !important;
    border: 1px solid var(--base-border-color) !important;
    &:hover {
      color: #fff !important;
      background-color: #3487ff !important;
    }
  }
  .el-tabs__item:not(.is-disabled):hover {
    color: var(--base-color);
  }
  .el-tabs__item:first-child {
    border-top-left-radius: 10px;
  }
  .el-tabs__item:last-child {
    text-align: center;
    border-top-right-radius: 10px;
  }
}

//-----
.cascaderPanel {
  overflow: auto;
  height: 400px;
  :deep(.el-cascader-menu) {
    width: 320px;
    max-width: 320px;
  }
  &:deep(.el-scrollbar__wrap) {
    height: 100% !important;
  }

  &.disabled {
    :deep(.el-cascader-node) {
      &::before {
        content: "";
        width: 40px;
        height: 100%;
        // background: pink;
        position: absolute;
        left: 10px;
        z-index: 99999;
      }
    }
  }
}
.tree {
  &.disabled {
    :deep(.el-tree-node) {
      &::before {
        content: "";
        width: 100px;
        height: 100%;
        position: absolute;
        left: 10px;
        z-index: 99999;
      }
    }
  }
}
:deep(.el-cascader-menu:last-child) {
  border-right: var(--el-cascader-menu-border);
}
:deep(.el-scrollbar__bar) {
  display: block !important;
}
</style>
